import axios from 'axios'
import qs from 'qs'
import {baseUrl} from './baseUrl'
import { Message, MessageBox } from 'element-ui' // MessageBox
import store from '../store'
// import mockdata from '@/api/mockdata'
// import router from '../router'

// 创建axios实例
const service = axios.create({
  baseURL: baseUrl,
  timeout: 5000, // 请求超时时间
  withCredentials: true
})
const service_upload = axios.create({
  baseURL: baseUrl,
  timeout: 20000, // 请求超时时间
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  withCredentials: true
})
const service_download = axios.create({
  baseURL: baseUrl,
  timeout: 20000, // 请求超时时间
  withCredentials: true
})
// const Mock = require('mockjs')
// mock
// const service_mock = (data) => {
//   return new Promise((resolve) => {
//     resolve(Mock.mock({ data: mockdata[data.url] }))
//   })
// }

// request拦截器
service.interceptors.request.use(
  config => {
    // if (store.getters.token) {
    //   config.headers['X-Token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    // }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data
    if (res.code !== 0) {
      if (res.code == '00000') {
        Message('系统版本授权过期，请获取授权后重试')
        setTimeout(() => {
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        }, 2000);
      } else if (res.code == '30001') {
        Message('没有权限操作')
      } else if (res.code == '10000') {
        Message('没有登录，请登录')
        setTimeout(() => {
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        }, 2000);
      } else {
        Message({
          message: res.msg,
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log(error)
    console.log('err' + error) // for debug
    Message({
      message: '网络错误',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)


service_upload.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.log(error)
    console.log('err' + error) // for debug
    Message({
      message: '网络错误',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

const http = {
  get(url, params = {}) {
    return service({
      url,
      method: 'get',
      params
    })
  },
  post(url, data = {}) {
    return service({
      url,
      method: 'post',
      data: data
    })
  },
  upload(url, data) {
    return service_upload({
      url,
      method: 'post',
      data
    })
  },
  download(url, fileName, data ={}) {
    service_download({
      url,
      method: 'post',
      data,
      responseType: 'blob', // important
    }).then((response) => {
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link) // 下载完成移除元素
      window.URL.revokeObjectURL(url) // 释放blob对象
    }).catch(err => {
      console.log('downloadError')
      console.log(err)
    })
  }
  // mock
  // getmock(url) {
  //   return service_mock({
  //     url
  //   })
  // },
  // postmock(url) {
  //   return service_mock({
  //     url
  //   })
  // }
}

export default http
